#include "tcpclientwidget.h"
#include "ui_tcpclientwidget.h"

#include <QDebug>
#include <QHostAddress>
#include <QMessageBox>

TcpClientWidget::TcpClientWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TcpClientWidget)
{
    ui->setupUi(this);
    ui->lineEditMsg->setDisabled(true);
    ui->pushButtonSend->setDisabled(true);
}

TcpClientWidget::~TcpClientWidget()
{
    delete ui;
}

void TcpClientWidget::on_pushButtonSend_clicked()
{
    tcpSocket->write(ui->lineEditUser->text().toUtf8() + " : " + ui->lineEditMsg->text().toUtf8());
    ui->lineEditMsg->clear();
}

void TcpClientWidget::on_pushButtonConnect_clicked()
{
    tcpSocket = new QTcpSocket(this);

    connect(tcpSocket, SIGNAL(connected()),
            this, SLOT(slotConnected()));
    connect(tcpSocket, SIGNAL(disconnected()),
            this, SLOT(slotDisconnect()));
    connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(slotError(QAbstractSocket::SocketError)));
    connect(tcpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this, SLOT(slotStateChanged(QAbstractSocket::SocketState)));

    connect(tcpSocket, SIGNAL(readyRead()),
            this, SLOT(slotReadData()));


    QHostAddress host(ui->lineEditServerIP->text());
    tcpSocket->connectToHost(host, ui->lineEditServerPort->text().toShort());
    //tcpSocket->waitForConnected();
    qDebug() << "connect success";
}

void TcpClientWidget:: slotReadData()
{
    while(tcpSocket->bytesAvailable() > 0){
        QByteArray temp;
        temp.resize(tcpSocket->bytesAvailable());

        tcpSocket->read(temp.data(), temp.size());

        ui->listWidgetText->addItem(QString(temp));
        ui->listWidgetText->scrollToBottom();
    }
}

void TcpClientWidget:: slotConnected()
{
    ui->lineEditMsg->setEnabled(true);
    ui->pushButtonSend->setEnabled(true);
}

void TcpClientWidget:: slotDisconnect()
{
    qDebug() << "connect lost";
    ui->pushButtonSend->setDisabled(true);
    ui->lineEditMsg->setDisabled(true);
}

void TcpClientWidget:: slotError(QAbstractSocket::SocketError err)
{
    qDebug() << err;
    QMessageBox::warning(this, "Warning", QString(err));
}

void TcpClientWidget:: slotStateChanged(QAbstractSocket::SocketState s)
{
    qDebug() << "State : " << s;
}
